import translators as ts
from typing import List
import logging

class Translator:
    def __init__(self, service: str = 'google'):
        """
        初始化翻译器
        :param service: 翻译服务提供商 (google, bing, deepl等)
        """
        self.service = service
        self.supported_services = ['google', 'bing', 'deepl', 'baidu', 'youdao']
        
        if service not in self.supported_services:
            logging.warning(f"不支持的翻译服务: {service}, 将使用google")
            self.service = 'google'
    
    def translate(self, text: str, from_lang: str = 'auto', to_lang: str = 'zh') -> str:
        """
        翻译单条文本
        :param text: 待翻译文本
        :param from_lang: 源语言 (auto为自动检测)
        :param to_lang: 目标语言
        :return: 翻译结果
        """
        try:
            return ts.translate_text(
                text,
                translator=self.service,
                from_language=from_lang,
                to_language=to_lang
            )
        except Exception as e:
            logging.error(f"翻译失败 ({self.service}): {str(e)}")
            return text
    
    def batch_translate(self, texts: List[str], from_lang: str = 'auto', to_lang: str = 'zh') -> List[str]:
        """
        批量翻译文本
        :param texts: 待翻译文本列表
        :param from_lang: 源语言
        :param to_lang: 目标语言
        :return: 翻译结果列表
        """
        try:
            # 如果只有一条文本，直接使用单条翻译
            if len(texts) == 1:
                return [self.translate(texts[0], from_lang, to_lang)]
            
            # 批量翻译更高效
            return ts.translate_text(
                texts,
                translator=self.service,
                from_language=from_lang,
                to_language=to_lang
            )
        except Exception as e:
            logging.error(f"批量翻译失败 ({self.service}): {str(e)}")
            return [self.translate(text, from_lang, to_lang) for text in texts]